package svgedit.gui;

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

import javax.swing.JComponent;

public class Listener extends JComponent {

	ArrayList<Shape> rects = new ArrayList<Shape>();

	Point startDragMouse, endDragMouse;

	public Listener() {

		this.addMouseListener(new MouseAdapter() 
		{
			public void mousePressed(MouseEvent event) 
			{
				startDragMouse = new Point(event.getX(), event.getY());
				endDragMouse = startDragMouse;
				repaint();
			}

			public void mouseReleased(MouseEvent event) 
			{
				Shape newRect = DrawRectangle(startDragMouse.x, startDragMouse.y, event.getX(), 
						event.getY());
				rects.add(newRect);
				startDragMouse = null;
				endDragMouse = null;
				repaint();
			}
		});

		this.addMouseMotionListener(new MouseMotionAdapter() 
		{
			public void mouseDragged(MouseEvent event) 
			{
				endDragMouse = new Point(event.getX(), event.getY());
				repaint();
			}
		});
	}

	public void paint(Graphics g) {
		Graphics2D g2D = (Graphics2D) g;
		//g2.setStroke(new BasicStroke(2)); //stroke width

		for (Shape rect : rects) {
			g2D.setPaint(Color.BLACK); //shape color
			g2D.draw(rect);
			//g2.fill(s); //fill color
		}

		if (startDragMouse != null && endDragMouse != null) 
		{
			g2D.setPaint(Color.BLACK); //change to color selected later
			Shape newShape = DrawRectangle(startDragMouse.x, startDragMouse.y, endDragMouse.x, endDragMouse.y);
			g2D.draw(newShape);
		}
	}

	private Rectangle2D.Float DrawRectangle(int x1, int y1, int x2, int y2) 
	{
		return new Rectangle2D.Float(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1 - x2), 
				Math.abs(y1 - y2));
	}
}
